package com.charles.ch_19;

public class GenericSort {
    public static void main(String[] args){
        Integer[] intArray = {new Integer(8),new Integer(3),new Integer(6)};
        Double[] doubleArray = {new Double(3.4),new Double(-4.6),new Double(1.2)};
        Character[] charArray = {new Character('c'),new Character('a'),new Character('d')};
        String[] stringArray = {"Jim","Tim","Kim"};

        sort(intArray);
        sort(doubleArray);
        sort(charArray);
        sort(stringArray);

        System.out.print("Sorted Integer Objects:");
        printList(intArray);

        System.out.print("Sorted Double Objects:");
        printList(doubleArray);

        System.out.print("Sorted Character Objects:");
        printList(charArray);

        System.out.print("Sorted String Objects:");
        printList(stringArray);
    }
    /*
    * 排序方法
    *
    * 泛型类型定义为：<E extends Comparable<E>>，这有两个含义：首先，它指定E是Comparable的子类型；
    * 其次，它还指定进行比较的元素是E类型的。
    * */
    public static <E extends Comparable<E>> void sort(E[] list){
        E currentMin;
        int currentMinIndex;
        for (int i = 0; i < list.length; i++) {
            currentMin = list[i];
            currentMinIndex = i;

            for (int j = i+1; j < list.length; j++) {
                if (currentMin.compareTo(list[j]) > 0){
                    currentMin = list[j];
                    currentMinIndex = j;
                }
            }
            if (currentMinIndex != i){
                list[currentMinIndex] = list[i];
                list[i] = currentMin;
            }
        }
    }

    public static void printList(Object[] list){
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }
        System.out.println();
    }
}
